# @time     :2022/1/18
# @Author   :Simple
# @FileName :market_page
from appium.webdriver.common.mobileby import MobileBy
from selenium.common.exceptions import NoSuchElementException

from common.element import GetElements
from common.element import find_child
from common.element import find_children
from xueqiu_demo.page.base_page import BasePage as base


class MarketPage(base):
    name_symbol_list = GetElements(xpath="//*[@resource-id='com.xueqiu.android:id/name_and_symbol']", describe="股票列表")
    price_list = GetElements(xpath="//*[@resource-id='com.xueqiu.android:id/row_recycler']", describe="股价列表")

    def get_stock(self):
        stock_list = []
        for index, ele in enumerate(self.name_symbol_list):
            stock_dict = {}
            name_loc = (MobileBy.XPATH, "//*[@resource-id='com.xueqiu.android:id/portfolio_stockName']")
            name = find_child(ele, name_loc).text
            code_loc = (MobileBy.XPATH, "//*[@resource-id='com.xueqiu.android:id/portfolio_stockCode']")
            code = find_child(ele, code_loc).text
            price_loc = (MobileBy.XPATH, "//*[@resource-id='com.xueqiu.android:id/item_layout']")
            price_change = find_children(self.price_list[index + 1], price_loc)
            if len(price_change) > 1:
                new_price = price_change[0].text
                change = price_change[1].text
            else:
                new_price_loc = (MobileBy.XPATH, "//*[@resource-id='com.xueqiu.android:id/portfolio_currentPrice']")
                new_price = find_child(self.price_list[index + 1], new_price_loc).text
                change_loc = (MobileBy.XPATH, "//*[@resource-id='com.xueqiu.android:id/portfolio_change']")
                change = find_child(self.price_list[index + 1], change_loc).text
            stock_dict['股票名'] = name
            stock_dict['股票代码'] = code
            stock_dict['最新价'] = new_price
            stock_dict['涨跌幅'] = change
            stock_list.append(stock_dict)
            # print(f"名称：{name}，代码：{code}，最新价：{new_price}，涨跌幅：{change}")
        return stock_list

